package com.qyer.search.utils;

import com.qyer.search.exception.InvalidFormatException;
import org.apache.commons.lang.StringUtils;

import java.util.*;
/**
 * Created by tangzheng on 16/3/7.
 */
public class SplitStringUtils {
  public static List<Integer> split(String source, String separator) throws Exception{
    if(StringUtils.isBlank(source))
      return new ArrayList<>();
    String[] tmp = source.split(separator);
    List<Integer> result = new ArrayList<>();
    try {
      for (int i = 0; i < tmp.length; i++) {
        int number = Integer.valueOf(tmp[i].trim());
        result.add(number);
      }
    }catch (Exception e){
      throw new InvalidFormatException("数据格式错误:" + e.getMessage());
    }
    return result;
  }

  public static Set<Integer> splitToSet(String source, String separator) throws Exception{
    if(StringUtils.isBlank(source))
      return new HashSet<>();
    if("null".equals(source))
      return new HashSet<>();
    source = source.replaceAll("[ ]*[，,\\,][ ]*", ",");
    String[] tmp = source.split(separator);
    Set<Integer> result = new HashSet<>();
    try {
      for (int i = 0; i < tmp.length; i++) {
        int number = Integer.valueOf(tmp[i].trim());
        result.add(number);
      }
    }catch (Exception e){
      e.printStackTrace();
      throw new InvalidFormatException("数据格式错误:" + e.getMessage());
    }
    return result;
  }

  public static  String[] splitTostrs(String source, String separator){
    if(StringUtils.isBlank(source))
      return null;
    return source.split(separator);
  }
}
